//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    winHeight: "",
    token: '',
    istokenPop: false, //判断是否等了
    tabIndex: 0,
    scrollTop: null, //坚挺scroolltop
    tabTop: "0",

    addStatus: false, //添加购物车操作

    dayList: [], //今日必看

    guanzhuList: [], //关注最高

    bannerList: [], //banner图

    isFixed: false,

    bookType: false,


    typeAll: false, //全部类型

    typeAll2: false, //全部排序类型

  params: {
      page: 1,
      size: 12,
      filterType:0,
      tag: "全部",
      sortType: 0,
      isFuzzySearch: false
    },
    bookList: [],
    // total: 0,
    curindex: 0
  },

  //banner监听事件
  swiperChange (e) {
    // console.log(e.detail.current)

    this.setData({
      curindex: e.detail.current
    })
  },

  //跳转消息
  openMsg () {
    wx.navigateTo({
      url: '/package/index/pages/msg/msg',
    })
  },
  //跳转卖书
  saoma () {
    wx.switchTab({
      url: '/pages/juanshu/juanshu',
    })
  },
  //搜索我想看的书
  bookSearch () {
    if (wx.getStorageSync('token') == '') {
      this.setData({
        istokenPop: true
      })
      return
    }
    wx.navigateTo({
      url: '/package/index/pages/bookSearch/bookSearch',
    })
  },
  //书本详情
  bookdetail (e) {
      console.log(e)


    // if (wx.getStorageSync('token') == '') {
    //   this.setData({
    //     istokenPop: true
    //   })
    //   return
    // }

      var bookId = e.currentTarget.dataset.bookid
      wx.navigateTo({
        url: '/package/index/pages/bookdetail/bookdetail?bookId=' + bookId,
      })
  },

  //获取标签高度
  getallHeight() {


     var that = this;
      var query = wx.createSelectorQuery()
      query.select('#affix').boundingClientRect()
      query.exec(function (res) {
        that.setData({
          menuTop: res[0]
        })
      })

  },

  //监听scroll
  onPageScroll (e) {
  //  console.log(e.scrollTop)
  //  this.setData({
  //    scrollTop: e.scrollTop,
  //    isFixed: this.data.tabTop - e.scrollTop < -1275 ? true: false
  //  })


    if (e.scrollTop > this.data.tabTop) {
        this.setData({
          isFixed: true
        })
    }else{
      this.setData({
        isFixed: false
      })
    }


  },


  // 头部tab切换
  tabClick (e) {
  console.log(e.currentTarget.dataset.tab)

  var _this = this
  var tabIndex = e.currentTarget.dataset.tab

    _this.setData({
      bookType: false,
      typeAll: false,
      typeAll2: false,
      tabIndex: tabIndex,
      params: {
        page: 1,
        size: 12,
        tag: "全部",
        sortType: 0,
        filterType: tabIndex == 0 ? 1 : tabIndex == 2 ? 2 : tabIndex == 3 ? 3 : "",
        isFuzzySearch: false
      },
      bookList: []
    })

    _this.getBooklist(_this.data.params)


    // setTimeout(function () {
    //   var query = wx.createSelectorQuery().in(_this);
    //   query.selectViewport().scrollOffset()
    //   query.select("#all_height").boundingClientRect();
    //   query.exec(function (res) {
    //     console.log(res);
    //     // var miss = res[1].height + 500
    //     wx.pageScrollTo({
    //       scrollTop: res[1].height - 10,
    //       duration: 300
    //     });

    //   })
    // }, 1000)

  },


  getAllbookType () {

      var bookType = this.data.bookType

      this.setData({
        bookType: !bookType
      })

  },


  clickAlltype () {
    var typeAll = this.data.typeAll

    this.setData({
      typeAll: !typeAll,
      typeAll2: false,
    })
  },


  clickAlltype2 () {
    var typeAll2 = this.data.typeAll2

    this.setData({
      typeAll2: !typeAll2,
      typeAll: false
    })
  },


  //加入购物车

  addShopcar (e) {
    console.log(e.currentTarget.dataset.bookid)


    if (wx.getStorageSync('token') == '') {
      this.setData({
        istokenPop: true
      })
      return
    }

    var bookid = e.currentTarget.dataset.bookid

     for (var i = 0; i < this.data.bookList.length; i++) {
       if (this.data.bookList[i].id == bookid) {
          this.addCarApi(bookid,i)
       }else{
         var iscllect = "bookList[" + i + "]addShop"
         this.setData({
           [iscllect]: false
         })
       }
     }


  },


  //添加购物车

  addCarApi (id,index) {

      var _this = this

    var params = {
      userId: wx.getStorageSync('userId'),
      bookInfoId: id
    }

    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/sdxShoppingTrolleys/mod/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
      "token" : wx.getStorageSync('token'),
        "uid" : wx.getStorageSync('uuid')
      },
      success: (res) => {
        console.log(res)

        if (res.data.code == 200) {
          var addShop = "bookList["+ index +"].addShop"

          _this.setData({
            [addShop]: true
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },



  //接口对接部分

  //获取今日必看列表
  getDaylist () {

    var _this = this
    var url = wx.getStorageSync('token') != '' ? 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/book/list/suggest/auth' :'https://devapi.xiaoshitimebank.com/user/sdx/sdx/book/list/suggest'
    wx.request({
      url: url,
      data: {},
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
      "token" : wx.getStorageSync('token'),
        "uid" : wx.getStorageSync('uuid')
      },
      success: (res) => {
        // console.log(res)
        if (res.data.code == 200) {
          wx.hideNavigationBarLoading() //完成停止加载

          wx.stopPullDownRefresh() //停止下拉刷新
          // var arr = []
          _this.setData({
             dayList: res.data.data.length < 5 ? res.data.data.slice(0,4) : res.data.data
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  //获取关注最高列表


  getGuanzhu () {
    var _this = this

    var url = wx.getStorageSync('token') != '' ? 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/book/list/most/follows/auth' : 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/book/list/most/follows'
    wx.request({
      url: url,
      data: {},
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
      "token" : wx.getStorageSync('token'),
        "uid" : wx.getStorageSync('uuid')
      },
      success: (res) => {
        console.log(res)

        if (res.data.code == 200) {
          wx.hideNavigationBarLoading() //完成停止加载

          wx.stopPullDownRefresh() //停止下拉刷新
          var arr = res.data.data
          _this.setData({
            guanzhuList: arr
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


 //获取书籍列表

getBooklist (params) {

  var _this = this
  var url = wx.getStorageSync('token') != '' ? 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/book/bookinfo/find/auth' :'https://devapi.xiaoshitimebank.com/user/sdx/sdx/book/bookinfo/find'
  wx.request({
    url: url,
    data: params,
    method: 'POST',
    header: {
      "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    "token" : wx.getStorageSync('token'),
      "uid" : wx.getStorageSync('uuid')
    },
    success: (res) => {
      if (res.data.code == 200) {
        wx.hideNavigationBarLoading() //完成停止加载

        wx.stopPullDownRefresh() //停止下拉刷新

        _this.setData({
          total: res.data.count
        })
        var arr = _this.data.bookList


        for (var i = 0; i < res.data.data.length;i++) {
          res.data.data[i].addShop = false
          arr.push(res.data.data[i])
        }
        // res.data.data.forEach(function (item,index) {
        //     arr.push(item)
        // })
        _this.setData({
          bookList: arr
        })
      }else{
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    }
  })
},


//获取banner

getBanner () {
  var _this = this
  wx.request({
    url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/publish/gets',
    data: {
      mainKey: 4
    },
    method: "POST",
    header: {
      "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    "token" : wx.getStorageSync('token'),
      "uid" : wx.getStorageSync('uuid')
    },
    success: (res) => {
      // console.log(res.data.su)
      console.log(res.data.data.length)


      if (res.data.success) {

        var arr = res.data.data
        _this.setData({
          bannerList: arr
        })
      }else{
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    }
  })
},

 //上啦加载更多
  onReachBottom () {
    if (this.data.bookList.length != this.data.total) {
      this.data.params.page += 1
      this.getBooklist(this.data.params)
    }
  },


  onShow () {

    var _this = this



    // setTimeout(function () {

    // },1500)

    this.getBanner()

    this.getDaylist()

    this.getGuanzhu()

    this.setData({
      token: wx.getStorageSync('token')
    })


    app.watch(this, {
      token: function (newVal, oldVal) {
   // console.log(newVal,oldVal)


        wx.pageScrollTo({
          scrollTop:0,
          duration: 300
        })
        this.getallHeight()

        var page = "params.page"
        var size = "params.size"
        this.setData({
          [page]: 1,
          [size]: 12,
          bookList: [],
        })

        this.getBooklist(this.data.params)
      }
    })


    // getApp().setWatcher(this.data, this.watch)
    // this.setData({
    //   token: wx.getStorageSync('token')
    // })


     //获取今日必看
  },




  //查询类型

  getTag (e) {
    console.log(e)


    var _this = this

    var datatag = e.currentTarget.dataset.tag

    var tag = "params.tag"

    this.setData({
      typeAll: false,
      typeAll2: false,
      [tag]: datatag
    })


    this.getBooklist(this.data.params)


    // setTimeout(function () {
    //   var query = wx.createSelectorQuery().in(_this);
    //   query.selectViewport().scrollOffset()
    //   query.select("#all_height").boundingClientRect();
    //   query.exec(function (res) {
    //     console.log(res);
    //     // var miss = res[1].height + 500
    //     wx.pageScrollTo({
    //       scrollTop: res[1].height - 50,
    //       duration: 300,
    //     });

    //   })
    // }, 1000)
  },

  // 综合排序


  allPaixu (e) {
    console.log(e)

    var _this = this

    var sort_type = e.currentTarget.dataset.sorttype
    var sorttype = "params.sortType"
    this.setData({
      typeAll2: false,
      [sorttype]: sort_type
    })
    this.getBooklist(this.data.params)


    // setTimeout(function () {
    //   var query = wx.createSelectorQuery().in(_this);
    //   query.selectViewport().scrollOffset()
    //   query.select("#all_height").boundingClientRect();
    //   query.exec(function (res) {
    //     console.log(res);
    //     // var miss = res[1].height + 500
    //     wx.pageScrollTo({
    //       scrollTop: res[1].height - 50,
    //       duration: 300,
    //     });

    //   })
    // }, 1000)
  },


  // 下拉刷新

  onPullDownRefresh: function () {


    wx.showNavigationBarLoading()

  var page = "params.page"
  var size = "params.size"
    this.setData({
      [page]: 1,
      [size]: 12,
      bookList: [],
    })

    this.onLoad()

    this.onShow()
  },

  onLoad (options) {


    console.log(options.scene)


    var _this = this
    this.getallHeight()
    this.getBooklist(this.data.params)

    if (wx.getStorageSync('token')!='') {
      if (options.scene) {
        var params = {
          sceneKey: decodeURIComponent(options.scene)
        }
        this.getKey(params)
      }
      if (options.userIds) {
        var params = {
          inviterId: options.userIds
        }
        this.getInvited(params)
      }
    }

  },

  getKey (params) {
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/scene/values/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.success) {
          var params = {
            inviterId: res.data.data.userId
          }
          _this.getInvited(params)
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  getInvited (params) {
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/scene/bindInviter/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.success) {
          console.log('绑定成功')
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  //取消弹框
  touchMove() {
    this.setData({
      istokenPop: true
    })
  },

  loginCode() {
    this.setData({
      istokenPop: false
    })

    var page = "params.page"
    var size = "params.size"
    this.setData({
      [page]: 1,
      [size]: 12,
      bookList: [],
    })

    this.onLoad()
    this.onShow()
  },


  // package/my/pages/shareFriends/shareFriends

  getActivity (e) {
    var key = e.currentTarget.dataset.key


    if (key == 1) {
      wx.navigateTo({
        url: '/package/index/pages/newTypelist2/newTypelist2'
      })
    }
    if (key == 2) {
      if (wx.getStorageSync('token') == '') {
        this.setData({
          istokenPop: true
        })
        return
      }
      wx.navigateTo({
        url: '/package/my/pages/shareFriends/shareFriends'
      })
    }
  },


  //跳转频道
  bookTypecat (e) {

    // if (wx.getStorageSync('token') == '') {
    //   this.setData({
    //     istokenPop: true
    //   })
    //   return
    // }

    var ageLeveType = e.currentTarget.dataset.agetype

    var titlename = e.currentTarget.dataset.titlename
    wx.navigateTo({
      url: '/package/index/pages/bookType/bookType?ageLeveType=' + ageLeveType + '&titlename=' + titlename,
    })
  },

  bookTypefenlei (e) {

    // if (wx.getStorageSync('token') == '') {
    //   this.setData({
    //     istokenPop: true
    //   })
    //   return
    // }
    var ageLeveType = e.currentTarget.dataset.agetype

    var titlename = e.currentTarget.dataset.titlename
    wx.navigateTo({
      url: '/package/index/pages/bookTypefenlei/bookTypefenlei?ageLeveType=' + ageLeveType + '&titlename=' + titlename,
    })
  },


  onShareAppMessage () {
    var that = this;

    return {

      title: '原价收书,二折买书',

      path: '/pages/index/index',

      imageUrl: 'https://timebank-prod-img.oss-cn-hangzhou.aliyuncs.com/Slx/1_sytp/syfxt.png',
      success: function (res) {

        console.log("转发成功:"  + JSON.stringify(res));

        wx.showToast({
          title: '转发成功',
          icon: 'none'
        })

        // that.shareClick();

      }
      }
  }

  // watch: {
  //   token: function (newValue) {
  //     if (newValue != null && newValue != '' && newValue!=undefined) {
  //       this.getallHeight()
  //       this.getBooklist(this.data.params)
  //    }
  //   }
  // }


})
